package abcy.cloud.blogcommon.builder;

import java.util.ArrayList;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Supplier;

public class TypeBuilder<T> {

    private final Supplier<T> type;

    private List<Consumer<T>> typeModifierLists = new ArrayList<>();

    public TypeBuilder(Supplier<T> type) {
        this.type = type;
    }

    public static <T> TypeBuilder<T> of(Supplier<T> type) {
        return new TypeBuilder<T>(type);
    }

    //将属性设置组装成Consumer。
    public <U> TypeBuilder<T> with(BiConsumer<T, U> biConsumer, U value) {
//        Consumer<T> consumer = t -> biConsumer.accept(t, value);
        Consumer<T> consumer = new Consumer<T>() {
            @Override
            public void accept(T t) {
                // 回调目标方法
                biConsumer.accept(t, value);
            }
        };
        this.typeModifierLists.add(consumer);
        return this;
    }


    public T build() {
        T type = this.type.get();
        // 将type传给所有的consumer, consumer接收到type后，执行biConsumer.accept(t,value), 然后回调setUserName。
//        this.typeModifierLists.forEach(tConsumer -> tConsumer.accept(type));
        this.typeModifierLists.forEach(new Consumer<Consumer<T>>() {
            @Override
            public void accept(Consumer<T> tConsumer) {
                tConsumer.accept(type);
            }
        });
        this.typeModifierLists.clear();
        return type;
    }
}